import EmptyContent from '@/components/EmptyContent';
import { enrollActivity, getMyActivityDetail } from '@/service/apis/mine';
import { View, Image, Text, Button } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { useEffect, useState } from 'react';
import { AtModal } from 'taro-ui';
import Modal from '@/components/Modal';
import successIcon from '@/assets/images/activity/success-icon.png';

import './style.scss';

/**
 * 活动详情页
 */
const ActivityDetail = () => {
  const $instance = Taro.getCurrentInstance();
  const { topic_id = '' } = $instance?.router?.params || {};
  const [data, setData] = useState<any>({});
  const isEnd = Date.now() - new Date(data.activity_end_time).getTime() > 0;
  const [hasJoin, setHasJoin] = useState(false);
  const [isShowModalSuccess, setIsShowModalSuccess] = useState(false);
  const [isShowSelectModal, setIsShowSelectModal] = useState(false);
  const [currentStoreId, setCurrentStoreId] = useState(0);
  const getActivityDetail = async () => {
    const { data } = await getMyActivityDetail({
      topic_id,
    });
    setData(data.topic);
    setHasJoin(data.join === 1);
  };

  useEffect(() => {
    getActivityDetail();
  }, []);

  // 报名活动
  const onEnroll = (storeId?: number) => {
    if (!storeId && currentStoreId === 0) return;
    setIsShowSelectModal(false);
    Taro.showModal({
      content: '确定报名这个活动吗',
      success: async function (res) {
        if (res.confirm) {
          const { data: resData } = await enrollActivity({
            topic_id: Number(topic_id),
            store_id: storeId || currentStoreId,
          });
          if (resData?.add_json) {
            setIsShowModalSuccess(true);
          } else {
            Taro.showToast({
              title: '已经参与过该门店的活动，请选择其他门店',
              icon: 'none',
            });
          }
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      },
    });
  };
  // 点击报名按钮
  const onClickEnroll = () => {
    if (isEnd) return;
    if (data.store_list.length > 1) {
      setIsShowSelectModal(true);
    } else {
      onEnroll(data.store_list[0].id);
    }
  };

  return (
    <View className="page-container">
      {!data && <EmptyContent />}
      {data && (
        <>
          <View className="activity-wrap">
            <Image className="activity-img" src={data.pic_url} />
            <View className="text-wrap">
              <View className="title-wrap">
                <Text className="type">活动</Text>
                <Text className="title">{data.title}</Text>
              </View>
              <View className="activity-time">
                活动时间：{data.activity_start_time} 到 {data.activity_end_time}
              </View>
              <View className="activity-time">联系人：{data.name}</View>
              <View className="activity-time">联系电话：{data.mobile}</View>
              <View className="activity-time">活动要求：{data.subtitle}</View>
            </View>
          </View>
          <View className="shop-wrap">
            <Text className="shop-wrap-title">参与门店 ({data?.store_list?.length}家)</Text>
            <View>
              {data?.store_list?.map((item, index) => (
                <View className="shop-item" key={index}>
                  <Image className="shop-img" mode="aspectFill" src={item.logo} />
                  <View className="text-wrap">
                    <Text className="shop-title">{item.store_name}</Text>
                    <Text className="shop-desc">{item.store_address}</Text>
                  </View>
                </View>
              ))}
            </View>
          </View>
          <View className="enroll-wrap">
            {data.status === 1 ? (
              <Button onClick={onClickEnroll} className={`${isEnd ? 'disable' : ''}`}>
                立即报名
              </Button>
            ) : (
              <Button onClick={onClickEnroll} className="disable">
                活动已结束
              </Button>
            )}
          </View>
        </>
      )}
      {/* 选择门店弹窗 */}
      <Modal
        title="请选择参与门店"
        show={isShowSelectModal}
        onClose={() => setIsShowSelectModal(false)}
        className="select-store-modal"
      >
        <View className="store-list">
          {data?.store_list?.map((item, index) => (
            <View
              key={index}
              onClick={() => setCurrentStoreId(item.id)}
              className={`store-item ${currentStoreId === item.id && 'active'}`}
            >
              {item.store_name}
            </View>
          ))}
        </View>
        <View
          className={`confirm-btn ${currentStoreId !== 0 && 'active'}`}
          onClick={() => onEnroll()}
        >
          确认
        </View>
      </Modal>
      {/* 预约成功弹窗 */}
      {isShowModalSuccess && (
        <AtModal className="success-modal" isOpened={isShowModalSuccess}>
          <Image className="success-icon" mode="widthFix" src={successIcon} />
          <Text className="success-title">恭喜您活动报名成功！</Text>
          <View
            onClick={() => {
              setIsShowModalSuccess(false);
              getActivityDetail();
            }}
            className="success-btn"
          >
            知道了
          </View>
        </AtModal>
      )}
    </View>
  );
};
export default ActivityDetail;
